package com.wh.wisdomsite.xbox.server.controller.pr;

import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.pr.UnitIn;
import com.wh.wisdomsite.xbox.pr.entity.Unit;
import com.wh.wisdomsite.xbox.pr.service.IUnitService;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.server.util.WrapperUtil;
import com.wh.wisdomsite.xbox.us.entity.Company;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

/**
 * 单位Controller
 *
 * @version V1.0
 * @Package: com.wh.wisdomsite.xbox.server.controller.us
 * @author: 丁奕
 * @date: 2018-08-03 15:49
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping(value = "/unit")
public class UnitController {

    private static final Log logger = LogFactory.getLog(UnitController.class);

    @Autowired
    private IUnitService iUnitService;

    /**
     * 页面跳转
     * @return
     */
    @RequiresPermissions("rules:pr_unit_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index(){
        return "/pr/unit/unitList";
    }

    /**
     * 获取单位集合
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:pr_unit_find")
    @RequestMapping(value = "/unitList.do")
    public void unitList(HttpServletResponse response, UnitIn in){
        try {
            logger.info("加载单位数据列表-->>开始");
            //设置分页
            if(in.getPage() == 0) in.setPage(1);
            if(in.getRows() == 0) in.setRows(10);
            Page<Unit> page = new Page<Unit>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            WrapperUtil<Unit> ewUnit = new WrapperUtil<Unit>();
            ewUnit.setEntity(new Unit());
            ewUnit.setTableAlias("u");
            if(StringUtils.isNotEmpty(in.getUnitName())){
                ewUnit.like("unitName", in.getUnitName());
            }
            if(StringUtils.isNotEmpty(in.getUnitOrgCode())){
                ewUnit.like("unitOrgCode", in.getUnitOrgCode());
            }
            if(StringUtils.isNotEmpty(in.getUnitModel())){
                ewUnit.eq("unitModel", in.getUnitModel());
            }
            if(StringUtils.isNotEmpty(in.getUnitProperty())){
                ewUnit.eq("unitProperty", in.getUnitProperty());
            }
            Company headCompany = UserUtils.getCurrentUserParentCompany();
            if(headCompany != null && headCompany.getCompanyId() != null){
                ewUnit.eq("companyId", headCompany.getCompanyId());
            }
            ewUnit.orderBy("uId", true);
            Page<Map<String, Object>> unitPage = iUnitService.getMapsPage(page, ewUnit);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if(unitPage.getRecords().size() > 0){
                for(Map<String, Object> unit : unitPage.getRecords()){
                    JSONObject object = new JSONObject(unit);
                    object.put("id",unit.get("uId"));
                    if(unit.get("parent") != null){
                        object.put("parent",new JSONObject(unit.get("parent")));
                    }
                    if(unit.get("unitModel") != null){
                        object.put("unitModel",new JSONObject(unit.get("unitModel")));
                    }
                    if(unit.get("unitProperty") != null){
                        object.put("unitProperty",new JSONObject(unit.get("unitProperty")));
                    }
                    if(unit.get("province") != null){
                        object.put("province",new JSONObject(unit.get("province")));
                    }
                    if(unit.get("city") != null){
                        object.put("city",new JSONObject(unit.get("city")));
                    }
                    if(unit.get("district") != null){
                        object.put("district",new JSONObject(unit.get("district")));
                    }
                    array.put(object);
                }
            }
            json.put("total",unitPage.getTotal());
            json.put("rows",array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载单位数据列表-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("加载单位数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 单位详情
     * @param unitIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:pr_unit_view")
    @RequestMapping("unitDesc.do")
    public String unitDesc(UnitIn unitIn, HttpServletRequest request) {
        logger.info("单位详情-->>开始");
        Map<String , Object> unit = iUnitService.getMapById(unitIn.getId());
        request.setAttribute("unit", unit);
        logger.info("单位详情-->>结束");
        return "/pr/unit/unitDesc";
    }

    /**
     * 跳转至添加或修改页面
     * @return
     */
    @RequestMapping("/toUnitOption")
    public String toUnitOption(String id, HttpServletRequest request){
        logger.info("添加修改单位跳转-->>开始");
        if(StringUtils.isNotEmpty(id)){
            //注入unit参数
            Unit unit = iUnitService.selectById(id);
            request.setAttribute("unit", unit);
        }
        logger.info("添加修改单位跳转-->>开始");
        return "pr/unit/unitOption";
    }

    /**
     * 更新或者修改
     * @param unit
     * @param response
     */
    @RequiresPermissions("rules:pr_unit_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(Unit unit,HttpServletResponse response){
        try {
            //若页面未设置parentId，则表示为跟节点
            if (unit.getuParentId() == null){
                //设置parentId为0
                unit.setuParentId(0);
            }
            //判断单位是否已经存在,存在即更新.否则为添加
            if(unit.getuId() != null){
                logger.info("修改单位-->>开始");
                iUnitService.updateById(unit);
                logger.info("修改单位-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("单位更新成功"));
            }else {
                logger.info("添加单位-->>开始");
                //设置其公司ID为当前用户的公司的ID
                unit.setCompanyId(UserUtils.getCurrentUserParentCompany().getCompanyId());
                unit.setUnitCode(UUID.randomUUID().toString().replace("-",""));
                iUnitService.insert(unit);
                logger.info("添加单位-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("单位添加成功"));
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("操作单位-->>Exception" + e.getMessage());
        }
    }

    /**
     * 删除单位
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:pr_unit_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String id, HttpServletResponse response){
        try{
            logger.info("删除单位-->>开始");
            iUnitService.deleteById(Integer.valueOf(id));
            logger.info("删除单位-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("单位删除成功"));
        } catch (Exception e){
            e.printStackTrace();
            logger.error("删除单位-->>Exception" + e.getMessage());
        }
    }


//    @RequestMapping(value = "/getUnitMapList.do", method = RequestMethod.GET)
//    public void getUnitMapList(HttpServletResponse response){
//        try{
//            logger.info("获取单位分类Map-->>开始");
//            Integer companyId = null;
//            Company company = UserUtils.getCurrentUserParentCompany();
//            if(company != null){
//                companyId = company.getCompanyId();
//            }
//            Map<String, List<Unit>> unitMapList = iUnitService.getUnitMapList(companyId);
//            logger.info("获取单位分类Map-->>结束");
//            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("获取单位分类Map成功"));
//        } catch (Exception e){
//            e.printStackTrace();
//            logger.error("获取单位分类Map-->>Exception" + e.getMessage());
//        }
//    }
}
